package com.lagou.rpc.balance;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @ClassName RpcLoadBanlance
 * @Description
 * @Author playboy
 * @Date 2021/6/5 4:43 下午
 * @Version 1.0
 **/
@Component
@ConfigurationProperties(prefix = "spring.rpc.server")
public class RpcLoadBanlance {

	private AtomicInteger index = new AtomicInteger(0);

	private String[] address;

	private InetSocketAddress[] inets;


	public void setAddress(String[] address) {
		this.address = address;
		inets = new InetSocketAddress[address.length];
		for (int i = 0; i < address.length; i++) {
			String[] split = address[i].split(":");
			InetSocketAddress inetSocketAddress = new InetSocketAddress(split[0], Integer.valueOf(split[1]));
			inets[i] = inetSocketAddress;
		}
	}

	public InetSocketAddress getAddress() {
		InetSocketAddress inetSocketAddress = inets[index.getAndAdd(1) % address.length];
		System.out.println("当前访问地址：" + inetSocketAddress.getHostString() + ":" + inetSocketAddress.getPort());
		return inetSocketAddress;
	}


}
